package com.gy.controller.result;

import com.alibaba.excel.EasyExcel;
import com.gy.controller.common.UserHolder;
import com.gy.entity.Export.CustomCellWriteHandler;
import com.gy.entity.Export.ExportField;
import com.gy.entity.Export.ExportRequest;
import com.gy.entity.result.Publication;
import com.gy.entity.result.Report;
import com.gy.query.PublicationQuery;
import com.gy.query.ReportQuery;
import com.gy.result.Result;
import com.gy.service.ReportService;
import com.gy.vo.PageVO;
import com.gy.vo.summary.ReportVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@Slf4j
@RequestMapping("/report")
@Api(tags = "新闻报道接口")
@CrossOrigin
public class ReportController {

    @Autowired
    private ReportService reportService;

    @PostMapping("/get/reportService")
    @ApiOperation("根据openid查看某个人的报道材料")
    public Result<PageVO<Report>> getReport(@RequestBody ReportQuery reportQuery){
        return reportService.getReportPage(reportQuery);
    }

    /**
     * 根据id主键删除新闻报道
     */
    @DeleteMapping("/deleteById/{id}")
    @ApiOperation("根据id主键删除新闻报道")
    public Result deleteById(@PathVariable Long id){
        return reportService.removeReport(id);
    }


    /**
     * 根据id主键查询新闻报道
     */
    @GetMapping("/getById/{id}")
    @ApiOperation("根据id主键查询新闻报道")
    public Result getById(@PathVariable Long id){
        return Result.success(reportService.getReportById(id));
    }

    /**
     * 更改新闻报道
     */
    @PutMapping("/update")
    @ApiOperation("更改新闻报道")
    public Result update(@RequestBody Report report){
        return reportService.updateReport(report);
    }

    /**
     * 新增新闻报道
     */
    @PostMapping("/save")
    @ApiOperation("新增新闻报道")
    public Result save(@RequestBody Report report){
        return reportService.saveReport(report);
    }

    /**
     * 根据多个id查询新闻报道
     */
    @PostMapping("/getByIds")
    @ApiOperation("根据多个id查询新闻报道")
    public Result getByIds(@RequestBody Long[] ids){
        return reportService.getReportByIds(ids);
    }

    /**
     * excel批量导出
     */
    @PostMapping("/export")
    @ApiOperation("excel批量导出")
    public void exportPersonalAward(@RequestBody ExportRequest request, HttpServletResponse response) throws IOException {
        List<ExportField> fields = request.getFields();
        List<Map<String, Object>> data = request.getData();

        String fileName = "exported_Report.xlsx";
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        // 动态生成表头
        List<List<String>> head = fields.stream()
                .map(field -> Arrays.asList(field.getLabel()))
                .collect(Collectors.toList());

        // 将 Map<String, Object> 转换为 List<List<Object>>
        List<List<Object>> transformedData = data.stream()
                .map(map -> fields.stream()
                        .map(field -> map.get(field.getKey()))
                        .collect(Collectors.toList()))
                .collect(Collectors.toList());

        // 写入数据
        EasyExcel.write(response.getOutputStream())
                .head(head)
                .registerWriteHandler(new CustomCellWriteHandler(fields))
                .sheet("新闻报道")
                .doWrite(transformedData);
    }

    /**
     * 获取新闻报道汇总信息
     */
    @GetMapping("/getSummary")
    @ApiOperation("获取新闻报道汇总信息")
    public Result<List<ReportVO>> getSummary() {
        Long userId = UserHolder.getUser().getUserId();
        if (userId == null) {
            return Result.error("用户未登录或信息异常");
        }

        // 查询新闻报道信息，并映射到 ReportVO
        List<Report> reportList = reportService.lambdaQuery()
                .eq(Report::getUserId, userId)
                .select(
                        Report::getTitle,
                        Report::getMediaLevel,
                        Report::getReportTime,
                        Report::getColumnSection,
                        Report::getOnlineLink,
                        Report::getMediaName
                )
                .list();

        // 数据转换，映射到 ReportVO
        List<ReportVO> reportVOList = reportList.stream()
                .map(report -> ReportVO.builder()
                        .title(report.getTitle())
                        .mediaLevel(report.getMediaLevel())
                        .reportTime(report.getReportTime())
                        .columnSection(report.getColumnSection())
                        .onlineLink(report.getOnlineLink())
                        .mediaName(report.getMediaName())
                        .build())
                .collect(Collectors.toList());

        return Result.success(reportVOList);
    }

}
